package cn.tedu.jdbc;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 获取结果集元数据信息，通过ResultSetMetaData来获取
 */
public class JDBCTest07 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;


        try {
            //1.创建连接
            Class.forName(driver);
            //2.获取连接
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("connection = " + conn);
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            System.out.println("statement = " + stmt);
            //4.执行SQL语句
            String sql = "select * from t_product";
            rs = stmt.executeQuery(sql);
            //5.处理结果集
            //通过结果集ResultSet来获取结果集元数据ResultSetMetaData
            //通过结果集元数据可以获取列的信息，例如：列名，列的数据类型，列的长度等等...
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            System.out.println("共" + columnCount + "列");
            //遍历每一列
            for (int i = 1;i<=columnCount;i++) {
                //i是列的下标。（注意：JDBC中所有的下标都是从1 开始的）
                //获取列名
                String columnName = rsmd.getColumnName(i);
                System.out.println("第" + i + "列的名字：" + columnName);
                //获取列的数据类型
                String columnTypeName = rsmd.getColumnTypeName(i);
                System.out.println("第" + i + "列的类型：" + columnTypeName);
                //获取列的长度
                int columnDisplaySize = rsmd.getColumnDisplaySize(i);
                System.out.println("第" + i + "列的长度：" + columnDisplaySize);
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}